package com.yihu.wlyy.web.doctor.consult;

import java.util.List;
import java.util.Map;

import com.yihu.wlyy.service.app.health.PatientHealthGuidanceService;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.consult.ConsultTeamLog;
import com.yihu.wlyy.entity.doctor.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.service.app.account.DoctorInfoService;
import com.yihu.wlyy.service.app.account.PatientInfoService;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.WeixinBaseController;

/**
 * 医生端：三师咨询控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/doctor/consult")
public class DoctorConsultController extends WeixinBaseController {

	@Autowired
	private ConsultTeamService consultTeamService;
	@Autowired
	private PatientInfoService patientService;
	@Autowired
	private DoctorInfoService doctorInfoService;
	@Autowired
	private PatientHealthGuidanceService patientHealthGuidanceService;

	/**
	 * 三师咨询列表查询
	 * @param type 咨询类型：0、全部，1、咨询我的，2、公共的， 3、参与过的，4、已结束的
	 * @param id
	 * @param pagesize 每页显示数，默认为10
	 * @return
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public String list(int type, int id, int pagesize, @RequestParam(required = false) String patient) {
		try {
			Page<ConsultTeam> list = consultTeamService.findByDoctor(getUID(), type, id, pagesize);
			JSONArray jsonArray = new JSONArray();
			for (ConsultTeam consult : list) {
				if (consult == null) {
					continue;
				}

				if (StringUtils.isNotBlank(patient) && !StringUtils.equals(patient, consult.getPatient())) {
					continue;
				}

				JSONObject json = new JSONObject();
				json.put("id", consult.getId());
				// 设置咨询标识
				json.put("consult", consult.getConsult());
				// 设置患者标识
				json.put("patient", consult.getPatient());
				// 设置患者头像
				json.put("photo", consult.getPhoto());
				// 设置咨询标识
				json.put("title", consult.getSymptoms());
				// 设置患者姓名
				json.put("name", consult.getName());
				// 设置患者年龄
				json.put("age", DateUtil.getAgeByBirthday(consult.getBirthday()));
				// 设置评价内容
				json.put("comment", consult.getCommentContent());
				// 设置评价星级
				json.put("star", consult.getCommentStar());
				// 设置咨询类型：1三师咨询，2家庭医生咨询
				json.put("type", consult.getType());
				// 设置咨询时间
				json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
				// 咨询状态
				json.put("status", consult.getStatus());
				// 设置性别
				json.put("sex", consult.getSex());
				// 未读消息
				json.put("doctorRead", consult.getDoctorRead());

				jsonArray.put(json);
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "查询失败！");
		}
	}

	/**
	 * 获取咨询全科医生签约量
	 *
	 * @param consults
	 * @return
	 */
	@RequestMapping(value = "/consult_sign")
	@ResponseBody
	public String consultSign(String consults){
		try{
            List<Map<String,Object>>  list = consultTeamService.getConsultSign(consults.split(","));
			return write(200,"查询成功","data",new JSONArray(list));
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"查询失败");
		}
	}

	/**
	 * 三师咨询转接接口
	 * @param consult 图咨询标识
	 * @param doctor 转接对象标识
	 * @param type 转接对象类型，1三师团队，2指定医生，3工作组团队  
	 * @return
	 */
	@RequestMapping(value = "transfer")
	@ResponseBody
	public String transfer(
			String consult, 
			String doctor, 
			@RequestParam(required = false)int type) {
		try {
			consultTeamService.transfer(getUID(), doctor, consult);
			return success("转接成功");
		} catch (Exception e) {
			error(e);
			return error(-1, "转接失败！");
		}
	}

	/**
	 * 结束三师咨询接口
	 * @param consult 三师咨询标识
	 * @return
	 */
	@RequestMapping(value = "finish")
	@ResponseBody
	public String finish(String consult) {
		try {
			int flag = consultTeamService.finish(consult);
			if (flag > 0) {
				return success("咨询已关闭");
			} else {
				return error(-1, "关闭失败！");
			}
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "关闭失败！");
		}
	}

	/**
	 * 设置消息已读
	 *
	 * @param consult
	 * @return
	 */
	@RequestMapping(value = "/readed")
	@ResponseBody
	public String readMessage(String consult){
		try{
			int result = consultTeamService.readMessage(consult);
			return write(200,"设置成功!");
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"设置失败");
		}
	}

	/**
	 * 医生咨询咨询日志查询
	 * @param consult 咨询标识
	 * @param patient 患者标识
	 * @param pagesize 每页显示数，默认为10
	 * @return
	 */
	@RequestMapping(value = "record")
	@ResponseBody
	public String record(String consult, String patient, long id, int pagesize) {
		try {
			Patient patientTemp = null;
			if (id <= 0) {
				// 只有第一页才会查询患者信息
				patientTemp = patientService.findByCode(patient);
				// 更新医生未读数量为0
				consultTeamService.clearDoctorRead(consult);
			}
			// 查询日志列表
			JSONArray jsonArray = new JSONArray();
			Page<ConsultTeamLog> list = consultTeamService.findLogByConsult(consult, id, pagesize);
			if (list != null) {
				for (ConsultTeamLog log : list) {
					if (consult == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", log.getId());
					// 设置回复内容
					json.put("content", log.getContent());
					// 设置回复医生姓名
					json.put("doctorName", log.getDoctorName());
					// 设置回复人头像
					json.put("photo", log.getPhoto());
					// 设置日志类型
					json.put("type", log.getType());
					// 设置记录类型
					json.put("chatType", log.getChatType());
					// 设置咨询或回复时间
					json.put("time", DateUtil.dateToStr(log.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
					jsonArray.put(json);
				}
			}
			// 设置返回结果
			JSONObject values = new JSONObject();
			if (patientTemp != null) {
				JSONObject patientJson = new JSONObject();
				// 设置患者标识
				patientJson.put("patient", patientTemp.getCode());
				// 设置姓名
				patientJson.put("name", patientTemp.getName());
				// 设置头像
				patientJson.put("photo", patientTemp.getPhoto());
				values.put("patient", patientJson);
			}
			values.put("list", jsonArray);
			// 返回结果
			return write(200, "查询成功", "data", values);
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "查询失败！");
		}
	}

	/**
	 * 医生回复网络咨询
	 * @param patient 患者标识
	 * @param consult 咨询标识
	 * @param content 回复内容
	 * @param type	回复类型，1文字，2图片，3语音
	 * @return
	 */
	@RequestMapping(value = "reply")
	@ResponseBody
	public String reply(String patient, String consult, String content, int type) {
		try {
			// 查询医生基本信息
			Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
			if (doctor == null) {
				return error(-1, "回复失败！");
			} else {
				ConsultTeamLog log = new ConsultTeamLog();
				// 设置咨询标识
				log.setConsult(consult);
				// 拷贝图片
				if (StringUtils.isNotEmpty(content)) {
					if (type == 3) {
						// 语音
						content = CommonUtil.copyTempVoice(content);
					} else if (type == 2) {
						// 图片
						content = CommonUtil.copyTempImage(content);
					}
				}
				// 设置回复内容
				log.setContent(content);
				log.setDel("1");
				// 设置回复医生标识
				log.setDoctor(doctor.getCode());
				// 设置医生姓名
				log.setDoctorName(doctor.getName());
				// 设置医生头像
				log.setPhoto(doctor.getPhoto());
				// 设置咨询类型为医生回复
				log.setType(1);
				// 设置记录类型
				log.setChatType(type);
				// 保存医生回复内容
				log = consultTeamService.reply(log, patient, getUID(), log.getType());
				if (log == null) {
					return error(-1, "回复失败！");
				} else {
					// 推送消息给患者
					// PushMsgTask.getInstance().put(patient, MessageType.MESSAGE_TYPE_PATIENT_CONSULT_TEAM_REPLY.P_CT_01.name(), MessageType.MESSAGE_TYPE_PATIENT_CONSULT_TEAM_REPLY.三师咨询.name(), MessageType.MESSAGE_TYPE_PATIENT_CONSULT_TEAM_REPLY.医生回复了您.name(), consult);
					// 推送消息给微信端
					ConsultTeam ct = consultTeamService.findByCode(consult);
					Patient p = patientService.findByCode(patient);
					if (ct != null && p != null && StringUtils.isNotEmpty(p.getOpenid())) {
						JSONObject json = new JSONObject();
						json.put("first", "问诊回复提醒");
						json.put("consultcontent", ct.getSymptoms());
						String replycontent = content.length() > 15 ? content.substring(0, 15) + "..." : content;
						if (type == 2) {
							replycontent = "[图片]";
						} else if (type == 3) {
							replycontent = "[语音]";
						}
						json.put("consult", consult);
						json.put("replycontent", replycontent);
						json.put("doctorName", doctor.getName());
						json.put("remark", "医生已为您提供问诊方案");
						PushMsgTask.getInstance().putWxMsg(getAccessToken(), 3, p.getOpenid(), p.getName(), json);
					}
					if (type == 2) {
						return write(200, "回复成功！", "data", content);
					}
					return success("回复成功！");
				}
			}
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "回复失败！");
		}
	}

	/**
	 * 查询医生的总咨询次数和今日咨询次数
	 * @param doctorCode
	 * @return
	 */
	@RequestMapping(value = "getConsultCount")
	@ResponseBody
	public String getAllCount(@RequestParam(required = true) String doctorCode) {
		try {
			JSONObject json = new JSONObject();
			Map<String,Long> counts=consultTeamService.getAllCount(doctorCode);
			
			json.put("all", counts.get("all"));
			json.put("today", counts.get("today"));
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "回复失败！");
		}
	}

	/**
	 * 查询患者的服务数目
	 * @return
     */
	@RequestMapping(value = "getPatientServicNum")
	@ResponseBody
	public String getPatientServicNum(String patientCode) {
		try {
			JSONObject json = new JSONObject();
			//统计咨询数目
			Integer allSize1=consultTeamService.findByDoctorSize(patientCode,getUID());
			//查询健康指导
			Integer allSize2=patientHealthGuidanceService.findGuidanceByPatient(patientCode,getUID());
			json.put("consult", allSize1);
			json.put("guide", allSize2);
			//json.put("today", counts.get("today"));
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "回复失败！");
		}
	}

}
